var toolInfoTableInit = function () {
    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#toolInfoTable').bootstrapTable({
            url: ctx + '/tool/toolInfo/listToolInfoByFilter/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop: false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect: false,                    //禁止多选
            checkboxHeader: true,                 //列头取消多选
            columns: [
                {
                    checkbox: true,
                    align: 'center',
                    valign: 'middle'
                },
                {
                    title: '序号',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        var options = $('#toolInfoTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                },
                {
                    field: 'status',
                    title: '状态',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value) {
                        if (value === '1') {
                            return '可使用'
                        } else if (value === '2') {
                            return '使用中'
                        } else if (value === '3') {
                            return '不可使用'
                        } else {
                            return ''
                        }
                    }

                }, {
                    field: 'toolCode',
                    title: '工装编码',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolName',
                    title: '工装名称',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'figureNo',
                    title: '图纸编号',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'applicationModelName',
                    title: '应用产品型号',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'enterFactoryDate',
                    title: '进厂日期',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'standardLife',
                    title: '标准寿命',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row) {
                        if (value) {
                            return value + (row.standardLifeUnit==='1'?'小时':'次');
                        } else {
                            return ""
                        }
                    }
                }, {
                    field: 'actualLife',
                    title: '使用寿命',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row) {
                        if (value) {
                            return value + (row.standardLifeUnit==='1'?'小时':'天');
                        } else {
                            return ""
                        }
                    }
                }, {
                    field: 'checkReportNo',
                    title: '验收报告编号',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'opName',
                    title: '使用工序',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'toolModel',
                    title: '工装型号',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'maintainFlag',
                    title: '保养',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value) {
                        if (value === '0') {
                            return '否'
                        } else if (value === '1') {
                            return '是'
                        } else {
                            return ''
                        }
                    }
                }, {
                    field: 'checkoutFlag',
                    title: '校验',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value) {
                        if (value === '0') {
                            return '否'
                        } else if (value === '1') {
                            return '是'
                        } else {
                            return ''
                        }
                    }
                }, {
                    field: 'repairType',
                    title: '维修方式',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value) {
                        if (value === '1') {
                            return '厂内维修'
                        } else if (value === '2') {
                            return '委外维修'
                        } else {
                            return ''
                        }
                    }
                }, {
                    field: 'dutyUserName',
                    title: '责任人',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: '',
                    title: '操作',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row) {
                        return "<a href='javascript:;' class='click_btn detail' data-pkid='" + row.pkId + "'>详情查看</a>";
                    }
                }, {
                    field: 'pkId',
                    title: 'pkId',
                    visible: false
                }]

        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset / params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            toolCode: $("#toolCode").val(),
            toolName: $("#toolName").val(),
            opCode: $("#operation").val(),
            //toolModel: $("#toolModel").val(),
            maintainFlag: $("#maintainFlag").val(),
            checkoutFlag: $("#checkoutFlag").val(),
            toolStatus: $("#status").val()
        };
    };
    return oTableInit;
};

jQuery(document).ready(function () {
    //1.初始化Table
    var oTable = new toolInfoTableInit();
    oTable.Init();
    //初始化页面
    toolInfoInit.init();
    //文件上传
    // fileUpload.init();
    batchImport.init();
});

var batchImport = function () {
    return {
        init: function () {
            batchImport._fileUpload();
        },

        _fileUpload: function () {
            $("#batchImportFile").fileinput({
                language: 'zh', //设置语言
                uploadUrl: ctx + '/tool/toolInfo/batchImportToolInfo/save.mvc', //上传的地址
                allowedFileExtensions: ['xls', 'xlsx'],//接收的文件后缀
                //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
                uploadAsync: true, //默认异步上传
                showUpload: false, //是否显示上传按钮
                showRemove: false, //显示移除按钮
                showPreview: true, //是否显示预览
                showCaption: false,//是否显示标题
                browseClass: "btn btn-primary", //按钮样式
                dropZoneEnabled: false,//是否显示拖拽区域
                maxFileSize: 10 * 1024,//单位为kb，如果为0表示不限制文件大小
                //minFileCount: 1,
                maxFileCount: 1, //表示允许同时上传的最大文件个数
                enctype: 'multipart/form-data',
                validateInitialCount: false,
                previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>",
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"

            }).on("fileuploaded", function (event, data, previewId, index) {//上传成功后立即执行
                console.log(data);
                var response = data.response;
                if (response.result === false) {
                    $("#batchImportTips").css("color","red");
                } else {
                    $("#batchImportTips").css("color","green");
                }
                $("#batchImportTips").css("display", "block");
                $("#batchImportTips").text(response.message);
                $('.btn-file').hide();
            }).on('filesuccessremove', function (event, id) {//点击删除后立即执行
                $('.btn-file').show();
                $("#batchImportTips").text("");
                $("#batchImportTips").css("display", "none");
            });
        }
    }
}();



// var fileUpload = function () {
//     return {
//         init: function () {
//             fileUpload._fileUpload();
//         },
//
//         _fileUpload: function () {
//             $("#uploadfile").fileinput({
//                 language: 'zh', //设置语言
//                 uploadUrl: ctx + '/tool/toolInfo/uploadFile/save.mvc', //上传的地址
//                 allowedFileExtensions: ['jpg', 'gif', 'png', 'txt', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'pot', 'pps', 'vsd', 'rtf', 'wps', 'et', 'dps', 'pdf', 'zip', 'rar'],//接收的文件后缀
//                 //uploadExtraData:{"id": 1, "fileName":'123.mp3'},
//                 uploadAsync: true, //默认异步上传
//                 showUpload: false, //是否显示上传按钮
//                 showRemove: false, //显示移除按钮
//                 showPreview: true, //是否显示预览
//                 showCaption: false,//是否显示标题
//                 browseClass: "btn btn-primary", //按钮样式
//                 dropZoneEnabled: false,//是否显示拖拽区域
//                 maxFileSize: 10 * 1024,//单位为kb，如果为0表示不限制文件大小
//                 //minFileCount: 1,
//                 maxFileCount: 1, //表示允许同时上传的最大文件个数
//                 enctype: 'multipart/form-data',
//                 validateInitialCount: false,
//                 previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>",
//                 msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
//
//             }).on("fileuploaded", function (event, data, previewId, index) {//上传成功后立即执行
//                 $("#toolInfoForm").find("input[name=fileName]").val(data.response.originalFileName);
//                 $("#toolInfoForm").find("input[name=filePath]").val(data.response.filePath);
//                 $(".error-tips").css("display", "none");
//                 $('.btn-file').hide();
//                 //   $(".file-input-new").attr("disabled",true);
//             }).on('filesuccessremove', function (event, id) {//点击删除后立即执行
//                 $("#toolInfoForm").find("input[name=fileName]").val('');
//                 $("#toolInfoForm").find("input[name=filePath]").val('');
//                 $('.btn-file').show();
//                 //$(".error-tips").css("display","block");
//             });
//         }
//     }
// }();

var toolInfoInit = function () {
    var operationSelect2;
    var dutyUserSelect2;
    var applicationModelSelect2;
    return {
        init: function () {
            SystemCommon.getSysDict("TOOL_TYPE", "tool-type");
            SystemCommon.getOperation();
            toolInfoInit._initOperationQuerySelect2();
            toolInfoInit._query();
            toolInfoInit._keyQuery();
            toolInfoInit._reset();
            toolInfoInit._refresh();
            toolInfoInit._add();
            toolInfoInit._update();
            toolInfoInit._delete();
            // toolInfoInit._download();
            operationSelect2 = toolInfoInit._initOperationSelect2();
            dutyUserSelect2 = toolInfoInit._initDutyUserSelect2();
            applicationModelSelect2 = toolInfoInit._initApplicationModelSelect2();
            toolInfoInit._validatorForm();
            toolInfoInit._validateFormExtend();
            toolInfoInit._save();
            toolInfoInit._initDateControl();
            toolInfoInit._detail();
            toolInfoInit._batchImport();
            toolInfoInit._downloadTemplate();
            toolInfoInit._modalHidden();

        },
        uploadImage:function(url){
            var previewJson =new Array();
            var preConfigList = new Array();
            console.log(url);
            var pkId = $("#pkId").val();
            if(url!="" && url!=null){
                previewJson.push("<img style='width:200px; height:150px;' src='/"+url+"'/>");
                var tjson = {
                    caption: "", // 展示的文件名
                    width: '100px',
                    url: ctx +'/equipment/register/delImage/del.mvc', // 删除url
                    key: pkId, // 删除是Ajax向后台传递的参数
                    extra: {}
                };
                preConfigList.push(tjson);
            };
            $("#uploadfile").fileinput('destroy');
            //文件上傳初始化
            $("#uploadfile").fileinput({

                language: 'zh', //设置语言

                uploadUrl: ctx +'/tool/toolInfo/uploadFile/save.mvc', //上传的地址

                allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀

                uploadAsync: true, //默认异步上传

                showUpload: false, //是否显示上传按钮
                showRemove :false, //显示移除按钮

                showPreview : true, //是否显示预览

                showCaption:false,//是否显示标题

                browseClass:"btn btn-primary", //按钮样式

                dropZoneEnabled: false,//是否显示拖拽区域

                showUploadedThumbs :true,

                maxFileSize:10*1024,//单位为kb，如果为0表示不限制文件大小

                maxFileCount: 10000, //表示允许同时上传的最大文件个数

                autoReplace : false,
                //圖片預覽
                initialPreview: previewJson,
                initialPreviewConfig: preConfigList,

                enctype:'multipart/form-data',

                validateInitialCount:false,

                previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>",

                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",

            }).on("fileuploaded", function (event, data, previewId, index){//上传成功后立即执行
                $("#toolInfoForm").find("input[name=fileName]").val(data.response.originalFileName);
                $("#toolInfoForm").find("input[name=filePath]").val(data.response.filePath);
                $(".error-tips").css("display", "none");
                $('.btn-file').hide();
            }).off('filesuccessremove').on('filesuccessremove', function(event, id) {//点击删除后立即执行
                console.log("del");
                $('.btn-file').show();
                $("#uploadfilePath").val("");
                $(".error-tips").css("display","block");
            }).off('filedeleted').on('filedeleted', function(event, key){//删除后的事件
                console.log("del");
                $('.btn-file').show();
                $("#uploadfilePath").val("");
                $(".error-tips").css("display","block");
            });
        },
        //条件查询
        _query: function () {
            $("#queryTool").on("click", function () {
                $('#toolInfoTable').bootstrapTable('refreshOptions', {
                    pageNumber: 1
                });
            });
        },
        //按键查询
        _keyQuery: function () {
            $(".tool-query").keypress(function (e) {
                if (e.which === 13) {
                    $("#queryTool").trigger("click");
                }
            });
        },
        //重置查询
        _reset: function () {
            $(".reset").on("click", function () {
                $(".clearfix input").val("");
                $("#status").val("");
                $(".clearfix input[type=checkbox]").prop("checked", "checked");
                $("#operation").val(null).trigger("change");
                $("#maintainFlag").val('');
                $("#checkoutFlag").val('');
            });
        },
        _refresh: function () {
            //刷新
            $("#refreshTable").on("click", function () {
                $('#toolInfoTable').bootstrapTable('refresh');
            });
        },
        //新增
        _add: function () {
            $("#add").on('click', function (e) {
                e.preventDefault();
                $('#myModal .title').html("新增");
                $.fn.modal.Constructor.prototype.enforceFocus = function () {
                    $("#myModal select").focus();
                };
                $("#toolInfoForm").find("input:radio[name=maintainFlag][value='1']").prop("checked", "checked");
                $("#toolInfoForm").find("input:radio[name=checkoutFlag][value='1']").prop("checked", "checked");
                $("#toolInfoForm").find("select[name=status]").val("1");
                toolInfoInit._changeMaintainValidate("1");
                toolInfoInit._changeCheckoutvalidate("1");
                var url = "";
                toolInfoInit.uploadImage(url);
                $('#myModal').modal();
            });
        },
        _initDateControl: function () {
            $('.form_datetime').datetimepicker({
                format: 'yyyy-mm-dd hh:ii:ss',
                language: 'zh-CN',
                autoclose: true,
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
            $('.form-date-time-day').datetimepicker({
                format: 'yyyy-mm-dd',
                minView: 2,
                autoclose: true,
                language: 'zh-CN',
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        _initOperationQuerySelect2: function () {
            $('#operation').select2({
                ajax: {
                    url: ctx + '/system/operation/listAllOperation/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            page: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (data) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test = [];
                        for (var int = 0; int < data.length; int++) {
                            var obj = {};
                            obj.id = data[int].code;
                            obj.text = data[int].name;
                            test.push(obj);
                        }
                        return {
                            results: test
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
        },
        _initOperationSelect2: function () {
            var select2 = $('#opCodeFormSelect2').select2({
                ajax: {
                    url: ctx + '/system/operation/listAllOperation/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            page: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (data) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test = [];
                        for (var int = 0; int < data.length; int++) {
                            var obj = {};
                            obj.id = data[int].code;
                            obj.text = data[int].name;
                            test.push(obj);
                        }
                        return {
                            results: test
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        _initDutyUserSelect2: function () {
            var select2 = $('#dutyUserFormSelect2').select2({
                ajax: {
                    url: ctx + '/system/user/getSysUserList/get.mvc',
                    dataType: 'json',
                    aynsc: false,
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            page: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (data) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test = [];
                        for (var int = 0; int < data.data.length; int++) {
                            var obj = {};
                            obj.id = data.data[int].username;
                            obj.text = data.data[int].truename;
                            test.push(obj);
                        }
                        return {
                            results: test
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        //删除
        _delete: function () {
            $("#delete").on("click", function () {
                var ids = $.map($('#toolInfoTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length < 1) {
                    DialogUtil.warning("请选择需要删除的记录");
                    return false;
                }
                var statusCollection = $.map($('#toolInfoTable').bootstrapTable('getSelections'), function (row) {
                    return row.status;
                });
                for (var i = 0; i < statusCollection.length; i++) {
                    if (statusCollection[i] === '2') {
                        DialogUtil.warning("使用中的工装不能删除");
                        return false;
                    }
                }
                DialogUtil.ok_and_cancel("是否确定删除记录？", function () {
                    $.ajax({
                        url: ctx + '/tool/toolInfo/deleteToolById/del.mvc',
                        type: "post",
                        dataType: 'json',
                        data: {
                            pkIds: ids.toString()
                        },
                        success: function (response) {
                            console.log(response);
                            if (response.result === true) {
                                DialogUtil.ok("删除成功");
                                $('#toolInfoTable').bootstrapTable('refresh');
                            } else {
                                DialogUtil.error(response.message);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            DialogUtil.error(errorThrown);
                        }
                    });
                }, function () {

                });
            });
        },
        //修改
        _update: function () {
            $("#update").on("click", function (e) {
                e.preventDefault();
                $('#myModal .title').html("修改");
                var ids = $.map($('#toolInfoTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                if (ids.length !== 1) {
                    DialogUtil.warning("请选择一行修改");
                    return false;
                }
                //解决select2无法输入问题
                $.fn.modal.Constructor.prototype.enforceFocus = function () {
                    $("#myModal select").focus();
                };
                //加载信息
                $.ajax({
                    url: ctx + "/tool/toolInfo/getToolInfoById/get.mvc",
                    type: "post",
                    dataType: "json",
                    data: {
                        pkId: ids.toString()
                    },
                    success: function (response) {
                        if (response.result === true && response.data) {
                            var _data = response.data;
                            $("#toolInfoForm").find("input[name=pkId]").val(_data.pkId);
                            $("#toolInfoForm").find("input[name=toolCode]").val(_data.toolCode);
                            $("#toolInfoForm").find("input[name=toolName]").val(_data.toolName);
                            $("#toolInfoForm").find("input[name=toolModel]").val(_data.toolModel);
                            $("#toolInfoForm").find("select[name=toolType]").val(_data.toolType);
                            $("#toolInfoForm").find("input[name=figureNo]").val(_data.figureNo);
                            $("#toolInfoForm").find("input[name=manufactor]").val(_data.manufactor);
                            $("#toolInfoForm").find("select[name=repairType]").val(_data.repairType);
                            $("#toolInfoForm").find("input[name=fileName]").val(_data.fileName);
                            $("#toolInfoForm").find("select[name=status]").val(_data.status);
                            $("#toolInfoForm").find("input[name=checkDate]").val(_data.checkDate);
                            $("#toolInfoForm").find("input[name=scrapDate]").val(_data.scrapDate);
                            //$("#toolInfoForm").find("input[name=applicationModel]").val(_data.applicationModelName);
                            $("#toolInfoForm").find("input[name=standardLife]").val(_data.standardLife);
                            $("#toolInfoForm").find("select[name=standardLifeUnit]").val(_data.standardLifeUnit);
                            // $("#standardLifeUnit").val(_data.standardLifeUnit);
                            $("#toolInfoForm").find("input[name=enterFactoryDate]").val(_data.enterFactoryDate);
                            $("#toolInfoForm").find("input[name=checkReportNo]").val(_data.checkReportNo);
                            if (_data.maintainFlag && _data.maintainFlag !== '') {
                                $("#toolInfoForm").find("input:radio[name=maintainFlag][value=" + _data.maintainFlag + "]").prop("checked", "checked");
                            }
                            toolInfoInit._changeMaintainValidate(_data.maintainFlag);
                            $("#toolInfoForm").find("input[name=maintainDate]").val(_data.maintainDate);
                            $("#toolInfoForm").find("input[name=maintainCycle]").val(_data.maintainCycle);
                            if (_data.checkoutFlag && _data.checkoutFlag !== '') {
                                $("#toolInfoForm").find("input:radio[name=checkoutFlag][value=" + _data.checkoutFlag + "]").prop("checked", "checked");
                            }
                            toolInfoInit._changeCheckoutvalidate(_data.checkoutFlag);
                            $("#toolInfoForm").find("input[name=checkoutDate]").val(_data.checkoutDate);
                            $("#toolInfoForm").find("input[name=checkoutCycle]").val(_data.checkoutCycle);
                            //初始化用户
                            var userId = _data.dutyUser;
                            var userName = _data.dutyUserName;
                            if (userId != null && userName != null) {
                                var option = new Option(userName, userId, true, true);
                                dutyUserSelect2.append(option);
                                dutyUserSelect2.trigger("change");
                            }
                            //初始化设备编码
                            var opCode = _data.opCode;
                            var opName = _data.opName;
                            if (opCode !== '' && opName !== '') {
                                var option = new Option(opName, opCode, true, true);
                                operationSelect2.append(option);
                                operationSelect2.trigger("change");
                            }

                            var applicationModel = _data.applicationModel;
                            var applicaitonModelName = _data.applicationModelName;
                            if (applicationModel != null && applicaitonModelName != null) {
                                var option = new Option(applicaitonModelName, applicationModel, true, true);
                                applicationModelSelect2.append(option);
                                applicationModelSelect2.trigger("change");
                            }
                            $("#toolInfoForm").find("input[name=filePath]").val(response.data.filePath);
                            var url = response.data.filePath;

                            toolInfoInit.uploadImage(url);
                            $('#myModal').modal();

                        } else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function () {
                        DialogUtil.error("系统繁忙！");
                    }
                });

            });
        },
        _initApplicationModelSelect2:function () {
            var select2 = $('#applicationModel').select2({
                ajax: {
                    url: ctx + '/tool/toolInfo/findProductModel/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            page: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response) {
                        var data = response.data;
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test = [];
                        for (var int = 0; int < data.length; int++) {
                            var obj = {};
                            obj.id = data[int].pkId;
                            obj.text = data[int].prodModel;
                            test.push(obj);
                        }
                        return {
                            results: test
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
            return select2;
        },
        _changeMaintainValidate: function (maintainFlag) {
            if (maintainFlag) {
                if ("1" === maintainFlag) {
                    $("#maintainDateDiv label").removeClass("form-required")
                        .removeClass("form-required-4")
                        .addClass("form-required")
                        .addClass("form-required-4");
                    $("#maintainCycleDiv label").removeClass("form-required")
                        .removeClass("form-required-6")
                        .addClass("form-required")
                        .addClass("form-required-6");
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('maintainDate', true);
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('maintainCycle', true);
                } else {
                    $("#maintainDateDiv label").removeClass("form-required")
                        .removeClass("form-required-4");
                    $("#maintainCycleDiv label").removeClass("form-required")
                        .removeClass("form-required-6");
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('maintainDate', false);
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('maintainCycle', false);
                }
            }
        },
        _changeCheckoutvalidate: function (checkoutFlag) {
            if (checkoutFlag) {
                if ("1" === checkoutFlag) {
                    $("#checkoutDateDiv label").removeClass("form-required")
                        .removeClass("form-required-4")
                        .addClass("form-required")
                        .addClass("form-required-4");
                    $("#checkoutCycleDiv label").removeClass("form-required")
                        .removeClass("form-required-6")
                        .addClass("form-required")
                        .addClass("form-required-6");
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('checkoutDate', true);
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('checkoutCycle', true);
                } else {
                    $("#checkoutDateDiv label").removeClass("form-required")
                        .removeClass("form-required-4");
                    $("#checkoutCycleDiv label").removeClass("form-required")
                        .removeClass("form-required-6");
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('checkoutDate', false);
                    $('#toolInfoForm').data('bootstrapValidator').enableFieldValidators('checkoutCycle', false);
                }
            }
        },
        //表单校验
        _validatorForm: function () {
            $("#toolInfoForm").bootstrapValidator({
                message: 'This value is not valid',
                live: 'submitted',
                fields: {
                    /*验证*/
                    toolCode: {
                        message: '工装编码无效',
                        validators: {
                            notEmpty: {
                                message: '工装编码不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '工装编码长度不能超过20个字符'
                            }
                        }
                    },
                    toolName: {
                        message: '工装名称无效',
                        validators: {
                            notEmpty: {
                                message: '工装名称不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '工装名称不能超过20个字符'
                            }
                        }
                    },
                    toolModel: {
                        message: '工装型号无效',
                        validators: {
                            notEmpty: {
                                message: '工装型号不能为空'
                            },
                            stringLength: {
                                max: 20,
                                message: '工装型号不能超过20个字符'
                            }
                        }
                    },
                    opCode: {
                        message: '工序无效',
                        validators: {
                            notEmpty: {
                                message: '使用工序不能为空'
                            }
                        }
                    },
                    toolType: {
                        message: '工装类别无效',
                        validators: {
                            notEmpty: {
                                message: '工装类别不能为空'
                            }
                        }
                    },
                    dutyUser: {
                        message: '责任人无效',
                        validators: {
                            notEmpty: {
                                message: '责任人不能为空'
                            }
                        }
                    },
                    repairType: {
                        message: '维修方式无效',
                        validators: {
                            notEmpty: {
                                message: '维修方式不能为空'
                            }
                        }
                    },
                    status: {
                        message: '状态无效',
                        validators: {
                            notEmpty: {
                                message: '状态不能为空'
                            }
                        }
                    },
                    maintainDate: {
                        trigger: 'change',
                        message: '保养开始无效',
                        validators: {
                            notEmpty: {
                                message: '保养开始不能为空'
                            }
                        }
                    },
                    maintainCycle: {
                        message: '保养周期无效',
                        validators: {
                            notEmpty: {
                                message: '保养周期不能为空'
                            },
                            regexp: {
                                regexp: /^[1-9]\d*$/,
                                message: '请输入正整数'
                            }
                        }
                    },
                    checkoutDate: {
                        trigger: 'change',
                        message: '保养开始无效',
                        validators: {
                            notEmpty: {
                                message: '校验开始不能为空'
                            }
                        }
                    },
                    checkoutCycle: {
                        message: '校验周期无效',
                        validators: {
                            notEmpty: {
                                message: '校验周期不能为空'
                            },
                            regexp: {
                                regexp: /^[1-9]\d*$/,
                                message: '请输入正整数'
                            }
                        }
                    }
                }
            });
        },
        _validateFormExtend: function () {
            $("#toolInfoForm").find("input[name=maintainFlag]").on("change", function () {
                var maintainFlag = $("#toolInfoForm").find("input[name=maintainFlag]:checked").val();
                toolInfoInit._changeMaintainValidate(maintainFlag);

            });
            $("#toolInfoForm").find("input[name=checkoutFlag]").on("change", function () {
                var checkoutFlag = $("#toolInfoForm").find("input[name=checkoutFlag]:checked").val();
                toolInfoInit._changeCheckoutvalidate(checkoutFlag);
            })
        },
        //保存
        _save: function () {
            $("#myModal .yes").on("click", function (e) {
                $("#myModal .yes").attr("disabled", true);
                e.preventDefault();
                $("#toolInfoForm").data("bootstrapValidator").validate();
                var flag = $("#toolInfoForm").data("bootstrapValidator").isValid();
                if (!flag) {
                    $("#myModal .yes").attr("disabled", false);
                    //未通过验证
                    return false;
                }
                var entity = {};
                entity['pkId'] = $("#toolInfoForm").find("input[name=pkId]").val();
                entity['status'] = $("#toolInfoForm").find("select[name=status]").val();
                entity['toolCode'] = $("#toolInfoForm").find("input[name=toolCode]").val();
                entity['toolName'] = $("#toolInfoForm").find("input[name=toolName]").val();
                entity['toolModel'] = $("#toolInfoForm").find("input[name=toolModel]").val();
                entity['opCode'] = $("#toolInfoForm").find("select[name=opCode]").val();
                entity['applicationModel'] = $("#toolInfoForm").find("select[name=applicationModel]").val();
                entity['standardLife'] = $("#toolInfoForm").find("input[name=standardLife]").val();
                entity['standardLifeUnit'] = $("#toolInfoForm").find("select[name=standardLifeUnit]").val();
                entity['enterFactoryDate'] = $("#toolInfoForm").find("input[name=enterFactoryDate]").val();
                entity['checkReportNo'] = $("#toolInfoForm").find("input[name=checkReportNo]").val();
                entity['toolType'] = $("#toolInfoForm").find("select[name=toolType]").val();
                entity['figureNo'] = $("#toolInfoForm").find("input[name=figureNo]").val();
                entity['manufactor'] = $("#toolInfoForm").find("input[name=manufactor]").val();
                entity['dutyUser'] = $("#toolInfoForm").find("select[name=dutyUser]").val();
                entity['fileName'] = $("#toolInfoForm").find("input[name=fileName]").val();
                entity['filePath'] = $("#toolInfoForm").find("input[name=filePath]").val();
                entity['repairType'] = $("#toolInfoForm").find("select[name=repairType]").val();
                entity['checkDate'] = $("#toolInfoForm").find("input[name=checkDate]").val();
                entity['scrapDate'] = $("#toolInfoForm").find("input[name=scrapDate]").val();
                entity['maintainFlag'] = $("#toolInfoForm").find("input:radio[name=maintainFlag]:checked").val();
                entity['maintainDate'] = $("#toolInfoForm").find("input[name=maintainDate]").val();
                entity['maintainCycle'] = $("#toolInfoForm").find("input[name=maintainCycle]").val() === null ? '' : $("#toolInfoForm").find("input[name=maintainCycle]").val();
                entity['checkoutFlag'] = $("#toolInfoForm").find("input:radio[name=checkoutFlag]:checked").val();
                entity['checkoutDate'] = $("#toolInfoForm").find("input[name=checkoutDate]").val();
                entity['checkoutCycle'] = $("#toolInfoForm").find("input[name=checkoutCycle]").val() === null ? '' : $("#toolInfoForm").find("input[name=checkoutCycle]").val();
                console.log(entity);
                $.ajax({
                    url: ctx + '/tool/toolInfo/saveOrUpdateToolInfo/save.mvc',
                    type: "post",
                    dataType: 'json',
                    data: entity,
                    success: function (response) {
                        if (response.result === true) {
                            DialogUtil.ok("保存成功");
                            //取消
                            $('#myModal').modal('hide');
                            $('#toolInfoTable').bootstrapTable('refresh');
                        } else {
                            DialogUtil.error(response.message);
                        }
                        $("#myModal .yes").attr("disabled", false);

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $("#myModal .yes").attr("disabled", false);
                        console.log(errorThrown);
                        DialogUtil.error("系统错误");
                    }
                });

            });
        },
        //文件下载
        _download: function () {
            $("#toolInfoTable").on("click", ".download", function (e) {
                e.preventDefault();
                e.stopPropagation();
                var pkId = $(this).data("pkid");
                window.location.href = ctx + "/equipment/document/downloadFile/get.mvc?pkId=" + pkId;

            });
        },
        _detail: function () {
            $("#toolInfoTable").on("click", "a.detail", function () {
                var pkId = $(this).data("pkid");
                console.log(pkId);
                $.ajax({
                    url: ctx + "/tool/toolInfo/getToolInfoById/get.mvc",
                    type: "post",
                    dataType: "json",
                    data: {
                        pkId: pkId
                    },
                    success: function (response) {
                        if (response.result === true && response.data) {
                            var _data = response.data;
                            $("#toolInfoDetailForm").find("input[name=pkId]").val(_data.pkId);
                            $("#toolInfoDetailForm").find("input[name=toolCode]").val(_data.toolCode);
                            $("#toolInfoDetailForm").find("input[name=toolName]").val(_data.toolName);
                            $("#toolInfoDetailForm").find("input[name=toolModel]").val(_data.toolModel);
                            $("#toolInfoDetailForm").find("input[name=toolType]").val(_data.toolTypeValue);
                            $("#toolInfoDetailForm").find("input[name=figureNo]").val(_data.figureNo);
                            $("#toolInfoDetailForm").find("input[name=manufactor]").val(_data.manufactor);
                            $("#toolInfoDetailForm").find("select[name=repairType]").val(_data.repairType);
                            $("#toolInfoDetailForm").find("input[name=fileName]").val(_data.fileName);
                            $("#toolInfoDetailForm").find("select[name=status]").val(_data.status);
                            $("#toolInfoDetailForm").find("input[name=checkDate]").val(_data.checkDate);
                            $("#toolInfoDetailForm").find("input[name=scrapDate]").val(_data.scrapDate);
                            $("#toolInfoDetailForm").find("input[name=maintainDate]").val(_data.maintainDate);
                            $("#toolInfoDetailForm").find("input[name=maintainCycle]").val(_data.maintainCycle);
                            $("#toolInfoDetailForm").find("input[name=applicationModel]").val(_data.applicationModelName);
                            $("#toolInfoDetailForm").find("input[name=standardLife]").val(_data.standardLife);
                            if(_data.standardLifeUnit==='1'){
                                $("#toolInfoDetailForm").find("input[name=standardLifeUnit]").val('小时');
                            }
                            if(_data.standardLifeUnit==='2'){
                                $("#toolInfoDetailForm").find("input[name=standardLifeUnit]").val('次');
                            }
                            $("#toolInfoDetailForm").find("input[name=enterFactoryDate]").val(_data.enterFactoryDate);
                            $("#toolInfoDetailForm").find("input[name=checkReportNo]").val(_data.checkReportNo);
                            if (_data.checkoutFlag && _data.checkoutFlag === '1') {
                                $("#toolInfoDetailForm").find("input[name=checkoutFlag]").val("是");
                            } else {
                                $("#toolInfoDetailForm").find("input[name=checkoutFlag]").val("否");
                            }
                            if (_data.maintainFlag && _data.maintainFlag === '1') {
                                $("#toolInfoDetailForm").find("input[name=maintainFlag]").val("是");
                            } else {
                                $("#toolInfoDetailForm").find("input[name=maintainFlag]").val("否");
                            }
                            $("#toolInfoDetailForm").find("input[name=checkoutDate]").val(_data.checkoutDate);
                            $("#toolInfoDetailForm").find("input[name=checkoutCycle]").val(_data.checkoutCycle);
                            //初始化用户
                            $("#toolInfoDetailForm").find("input[name=dutyUser]").val(_data.dutyUserName);
                            $("#toolInfoDetailForm").find("input[name=opCode]").val(_data.opName);
                            var url = window.location.host;
                            $("#imageId").attr("src","http://"+url+"/"+response.data.filePath);
                            $('#detailModal').modal();

                        } else {
                            DialogUtil.error(response.message);
                        }
                    },
                    error: function () {
                        DialogUtil.error("系统繁忙！");
                    }
                });
            })
        },
        _batchImport:function () {
            $("#batchImport").on("click",function () {
                $("#batchImportModal").modal();
            })
        },
        _downloadTemplate:function () {
            $("#downloadTemplate").on("click",function () {
                window.location.href = ctx +"/tool/toolInfo/downloadImportTemplate/get.mvc"
            })
        },
        _modalHidden: function () {
            //模态框消失清空信息
            $("#myModal").on("hide.bs.modal", function (e) {
                $('#myModal input').each(function () {
                    if ($(this).val() !== "" && $(this).attr("name") !== 'checkoutFlag' && $(this).attr("name") !== 'maintainFlag') {
                        $(this).val("");
                    }

                });
                $("#toolInfoForm").find("select[name=status]").val("1");
                $("#toolInfoForm").find("select[name=repairType]").val("");
                $('#opCodeFormSelect2').val(null).trigger("change");
                $('#dutyUserFormSelect2').val(null).trigger("change");
                $('#applicationModel').val(null).trigger("change");
                $('.tool-type').val(null).trigger("change");

                $("#toolInfoForm").find("input:radio[name=maintainFlag][value='1']").prop("checked", "checked");
                $("#toolInfoForm").find("input:radio[name=checkoutFlag][value='1']").prop("checked", "checked");
                $('.btn-file').show();
                $('.fileinput-remove').trigger('click');
                $('#toolInfoForm').bootstrapValidator('resetForm', false);
            });

            $("#detailModal").on("hide.bs.modal", function (e) {
                $('#detailModal input').each(function () {
                    if ($(this).val() !== "") {
                        $(this).val("");
                    }
                });
                $('#detailModal select').each(function () {
                    $(this).val("");
                })
            });
            $("#batchImportModal").on("hide.bs.modal",function(){
                $('.btn-file').show();
                $('.fileinput-remove').trigger('click');
                $('.error-tips').css("display", "none");
            });
        }

    }
}();